package cn.idietrade.idietradegateway9527.utils;

import cn.idietrade.common.utils.EmptyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.logging.Logger;

/**
 * @author zjy
 * @version 1.0
 * @createTime 2022-12-05 15:56
 * @description
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Resource
    private RedisUtil redisUtil;

    Logger logger =Logger.getLogger("TokenFilter");
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri = exchange.getRequest().getURI().toString();

        String str1=null;
        String token =null;
        //截取token=之后字符串
        if(uri.indexOf("token=")>0){
            str1 = uri.substring(0, uri.indexOf("token="));
            token= uri.substring(str1.length()+1, uri.length());
        }

        //String token = exchange.getRequest().getHeaders().getFirst("token");

        String url_1 = "/user/login";
        String url_2 = "/user/register";
        String url = exchange.getRequest().getURI() + "";
        //为登录时直接继续执行
        if(url.contains(url_1)){
            return chain.filter(exchange);
        } else if (url.contains(url_2)) { //为注册时候也放心
            return chain.filter(exchange);
        }
        if (EmptyUtils.isEmpty(token)) {
            return chain.filter(exchange);
        }

        //token信息为空时
        if (EmptyUtils.isNotEmpty(token)) {
            //redis没有该token时
            if (EmptyUtils.isNotEmpty(redisUtil.getStr(token))){
                //token不为空并且redis中不过期 继续执行
                return chain.filter(exchange);
            }else{
                logger.info("-----token不为空 redis中已过期-----");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        }else{
            logger.info("-----token为空-----");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

    }


    @Override
    public int getOrder() {
        return 0;
    }
}
